<?php

namespace app\qsapi\model;

use think\cache\driver\Redis;

class BoxMemberInfo extends BaseModel
{
    public $member_score_key = "MEMBER_SCORE_[MEMBERID]";

    /**
     * 更新用户redis积分字段
     * @param $member_id
     * @param $score
     * @return void
     */
    public function incOrDecMemberScoreRedis($member_id, $score){
        $key = str_replace("[MEMBERID]", $member_id, $this->member_score_key);
        $redis = new Redis(getRedisConfig());
        if ($score > 0){
            $redis->inc($key, $score);
        } else {
            $redis->dec($key, $score);
        }
    }

    /**
     * 更新用户数据库积分字段
     * @param $member_id
     * @param $score
     * @return void
     * @throws \think\Exception
     */
    public function incOrDecMemberScore($member_id, $score){
        if ($score > 0){
            $this->where("member_id", "=", $member_id)->setInc("score", $score);
        } else {
            $this->where("member_id", "=", $member_id)->setDec("score", $score);
        }
    }

    /**
     * 查询用户的积分值
     * @param $member_id
     * @return mixed
     */
    public function getMemberScore($member_id){
        $redis = new Redis(getRedisConfig());
        $key = str_replace("[MEMBERID]", $member_id, $this->member_score_key);
        $score = $redis->get($key);
        if (empty($score)){
            //从数据库中查询对应的score值
            $score = $this->where("member_id", "=", $member_id)->value("score");
            //设置缓存
            $redis->set($key, $score);
        }
        return $score;
    }

    /**
     *
     * @param $member_id
     * @param $type
     * @param $score
     * @param $before
     * @return void
     */
    public function addMemberScoreLog($member_id, $type, $score, $before){
        $index_key = "MEMBER_SCORE_LOG_INDEX";
        $log_key = "MEMBER_SCORE_LOG";
        $redis = new Redis(getRedisConfig());

        $index = $redis->inc($index_key);
        $data = array(
            "member_id" => intval($member_id),
            "type" => intval($type),
            "score" => intval($score),
            "before" => intval($before),
            "time" => date("Y-m-d H:i:s"),
            "index" => $index
        );
        $redis->zAdd($log_key, $index, json_encode($data));
    }

}